<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-content">
        <h2 class="login-title">系统登录</h2>
        <el-form ref="loginFormRef"
                 :model="loginForm"
                 :rules="loginRules"
                 class="login-form">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username"
                      :prefix-icon="User"
                      placeholder="请输入用户名"
                      size="large" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="loginForm.password"
                      :prefix-icon="Lock"
                      type="password"
                      placeholder="请输入密码"
                      size="large"
                      show-password
                      @keyup.enter="handleLogin" />
          </el-form-item>

          <el-form-item prop="captcha">
            <div class="captcha-container">
              <el-input v-model="loginForm.captcha"
                        placeholder="请输入验证码"
                        size="large" />
              <div class="captcha-img"
                   @click="refreshCaptcha">
                <img :src="captchaImg"
                     alt="验证码"
                     v-if="captchaImg">
                <el-icon v-else>
                  <Loading />
                </el-icon>
              </div>
            </div>
          </el-form-item>

          <div class="login-btns">
            <el-button type="primary"
                       :loading="loading"
                       @click="handleLogin"
                       size="large"
                       class="submit-btn">
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
            <el-button @click="resetForm"
                       size="large"
                       class="reset-btn">
              重置
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock, Loading } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getVerifyCodeApi, loginApi } from '@/api/auth'
import { UserLogin } from '@/api/auth/type'
import { useUserAuthStore } from '@/store/modules/auth'

const userAuthStore = useUserAuthStore()
const router = useRouter()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)

// 登录表单数据
const loginForm = reactive<UserLogin>({
  username: '13389653201',
  password: 'liujin20024788',
  captcha: '',
  captchaKey: '',
})

const captchaImg = ref('')

// 表单校验规则
const loginRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}

// 登录方法
const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      try {
        const result = await loginApi(loginForm)
        await userAuthStore.setToken(result.data)
        ElMessage.success('登录成功')
        router.push('/')
      } catch (error) {
        console.error('登录失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!loginFormRef.value) return
  loginFormRef.value.resetFields()
}

// 获取验证码
const getCaptcha = async () => {
  try {
    const res = await getVerifyCodeApi()
    if (res.data) {
      captchaImg.value = res.data.captchaBase64
      loginForm.captchaKey = res.data.captchaKey
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  getCaptcha()
}

onMounted(() => {
  getCaptcha()
})
</script>

<style scoped lang="scss">
.login-container {
  height: 100vh;
  width: 100vw;
  background: url('@/assets/loginBackground.jpg') no-repeat center center;
  background-size: cover;
  display: flex;
  align-items: center;

  .login-box {
    width: 500px;
    margin-left: 7%;
    padding: 40px;

    .login-content {
      background: rgba(255, 255, 255, 0.9);
      backdrop-filter: blur(10px);
      border-radius: 8px;
      padding: 40px;
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);

      .login-title {
        text-align: center;
        color: #303133;
        margin-bottom: 40px;
        font-size: 28px;
        font-weight: 600;
      }

      .login-form {
        .el-form-item {
          margin-bottom: 25px;
        }

        .el-input {
          --el-input-hover-border-color: #409eff;
          --el-input-focus-border-color: #409eff;

          .el-input__wrapper {
            box-shadow: 0 0 0 1px #dcdfe6 inset;
            transition: all 0.3s;

            &:hover,
            &.is-focus {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }

        .captcha-container {
          display: flex;
          gap: 12px;

          .el-input {
            flex: 1;
          }

          .captcha-img {
            width: 120px;
            height: 40px;
            cursor: pointer;
            border-radius: 4px;
            overflow: hidden;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
        }

        .login-btns {
          display: flex;
          gap: 15px;
          margin-top: 40px;

          .submit-btn,
          .reset-btn {
            flex: 1;
            height: 44px;
            font-size: 16px;
          }

          .submit-btn {
            background: linear-gradient(45deg, #409eff, #36d1dc);
            border: none;

            &:hover {
              opacity: 0.9;
              transform: translateY(-1px);
            }
          }

          .reset-btn {
            &:hover {
              border-color: #409eff;
              color: #409eff;
            }
          }
        }
      }
    }
  }
}
</style>
